package com.itcast.activiti.event.listener;

import com.alibaba.fastjson.JSONObject;
import com.itcast.activiti.domain.Attachment;
import com.itcast.activiti.event.CreateAttachmentEvent;
import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.TaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

/**
 * 添加附件
 */
@Slf4j
@Component
public class CreateAttachmentListener {
    @Autowired
    private TaskService taskService;

    @EventListener
    public void execute(CreateAttachmentEvent event) {
        log.info("CreateAttachmentListener {}", JSONObject.toJSON(event));
        Attachment attachment = event.getAttachment();
        if (null == attachment) {
            return;
        }
        try {
            if (StringUtils.hasText(attachment.getContent())) {
                taskService.createAttachment(
                        attachment.getAttachmentType(),
                        StringUtils.hasText(attachment.getTaskId()) ? attachment.getTaskId() : event.getTaskId(),
                        StringUtils.hasText(attachment.getProcessInstanceId()) ? attachment.getProcessInstanceId() : event.getProcessInstanceId(),
                        attachment.getAttachmentName(),
                        attachment.getAttachmentDescription(),
                        attachment.getContent());
            } else {
                // 附件流
                taskService.createAttachment(
                        attachment.getAttachmentType(),
                        StringUtils.hasText(attachment.getTaskId()) ? attachment.getTaskId() : event.getTaskId(),
                        StringUtils.hasText(attachment.getProcessInstanceId()) ? attachment.getProcessInstanceId() : event.getProcessInstanceId(),
                        attachment.getAttachmentName(),
                        attachment.getAttachmentDescription(),
                        attachment.getFile());
            }
        } catch (Exception e) {
            log.warn("添加附件 Exception {}", e.getMessage());
        }
    }


}
